package com.video.service.client.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.video.entity.ClientGroup;
import com.video.entity.ClientGroupTable;
import com.video.entity.ClientMsg;
import com.video.entity.TreeNode;
import com.video.mapper.ClientGroupMapper;
import com.video.mapper.ClientGroupMiddleMapper;
import com.video.mapper.ClientMsgMapper;
import com.video.service.client.IClientGroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class ClientGroupServiceImpl extends ServiceImpl<ClientGroupMapper, ClientGroup> implements IClientGroupService {

    @Autowired
    private ClientGroupMapper clientGroupMapper;

    @Autowired
    private ClientMsgMapper clientMsgMapper;

    @Autowired
    private ClientGroupMiddleMapper clientGroupMiddleMapper;

    @Override
    @Transactional
    public int insert(ClientGroup clientGroup) {
        int result = clientGroupMapper.insert(clientGroup);
        return result;
    }

    /**
     * 查询所有分组以及分组下的所有终端
     * @return
     */
    @Override
    @Transactional(readOnly = true)
    public List<TreeNode> queryAllGroup() {
        List<TreeNode> treeNodes = new ArrayList<>();
        //查询所有分组以及分组下的终端
        List<ClientGroup> clientGroups = clientGroupMapper.queryAllGroupJoinClient();
        for (ClientGroup clientGroup : clientGroups) {
            //创建分组的树型对象
            TreeNode treeNode = new TreeNode()
                    .setId(clientGroup.getId())
                    .setPid(clientGroup.getPid())
                    .setGname(clientGroup.getGname())
                    .setIsParent("true")
                    .setIcon("");

            treeNodes.add(treeNode);
            //处理分组下的终端
            if(clientGroup.getClientMsgs() != null){
                //循环处理所有终端
                for (ClientMsg clientMsg : clientGroup.getClientMsgs()) {
                    //将终端转换成树型对象
                    TreeNode clientTreeNode = new TreeNode()
                            .setUserid(clientMsg.getUserid())
                            .setPid(clientGroup.getId())
                            .setGname(clientMsg.getTerminalname() != null ? clientMsg.getTerminalname() : clientMsg.getUserid() + "")
                            .setIcon(clientMsg.getStatus() == 1 ? "/commons/images/online2.png" : "/commons/images/offline2.png")
                            .setIsClient(1)
                            .setIsOnLine(clientMsg.getStatus())
                            .setHosts(clientMsg.getHosts());
//                            .setChecked(clientMsg.getHosts() == 1);

                    treeNodes.add(clientTreeNode);
                }
            }
        }

        return treeNodes;
    }

    /**
     * 删除群组或者终端
     * @param id
     * @param gid
     * @param isClient
     * @return
     */
    @Override
    @Transactional
    public int deleteGroupOrClient(Integer id, Integer gid, boolean isClient) {
        if(!isClient){
            //操作的是群组
            //删除群组
            clientGroupMapper.deleteById(id);
            //该群组下的子群组设置为顶级群组
            UpdateWrapper updateWrapper = new UpdateWrapper();
            updateWrapper.eq("pid", id);
            clientGroupMapper.update(new ClientGroup().setPid(-1), updateWrapper);
            //根据群组id查询该组下的所有终端id
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("gid", id);
            List<ClientGroupTable> clientGroupTables = clientGroupMiddleMapper.selectList(queryWrapper);

            //修改组员成默认组
            for (ClientGroupTable clientGroupTable : clientGroupTables) {
                //判断该设备是否存在于默认组
                int result = clientGroupMiddleMapper.update2DefaultGroupId(clientGroupTable.getCid(), id);
                //
                if(result == 0){
                    //删除中间表
                    deleteClientGroupTable(clientGroupTable.getCid(), id);
                }
            }

        } else {
            //操作的就是终端
            //删除中间表
            deleteClientGroupTable(id, gid);
        }
        return 1;
    }

    @Override
    public int move(Integer[] ids, Integer pid, Integer oldpid, boolean isClient, boolean isCopy) {
        if (isClient){
            for (Integer id : ids) {
                //如果不是复制操作，则必须将终端与原来群组的关系删除掉
                if(!isCopy){
                    //删除中间表
                    deleteClientGroupTable(id, oldpid);
                }

                //添加终端和新群组的关系
                ClientGroupTable clientGroupTable = new ClientGroupTable(id, pid);
                clientGroupMiddleMapper.insert(clientGroupTable);
            }
        } else {
            //移动的是群组
            ClientGroup group = clientGroupMapper.selectById(ids[0]);
            group.setPid(pid);
            clientGroupMapper.updateById(group);
        }
        return 1;
    }

    /**
     * 删除群组中间表
     * @return
     */
    private int deleteClientGroupTable(Integer cid, Integer gid){
        QueryWrapper deleteWraper = new QueryWrapper();
        deleteWraper.eq("cid", cid);
        deleteWraper.eq("gid", gid);
        return clientGroupMiddleMapper.delete(deleteWraper);
    }
}
